package com.ymatou.iapi.trading.operate.testcase;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.json.JSONArray;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.PlatformEnum;
import com.ymatou.iapi.trading.operate.parameter.req.OrderPayCallBackReq;
import com.ymatou.iapi.trading.operate.parameter.req.OrderPayRequestBean;
import com.ymatou.iapi.trading.operate.service.OrderPayCallBackCall;
import com.ymatou.iapi.trading.operate.service.OrderPayRequestCall;
import com.ymatou.operate.trading.api.parameter.PlaceOrderBean;
import com.ymatou.operate.trading.api.service.PlaceOrderCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.business.data.Sign;
import com.ymttest.business.service.CouponCallService;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.ProductCallService;
import com.ymttest.common.entitie.OrderInfo;
import com.ymttest.common.entitie.OrderProductInfo;
import com.ymttest.common.entitie.ProductActivityInfo;
import com.ymttest.common.enums.ActivityPromotionTypeEnum;
import com.ymttest.common.enums.AppTerminalSourceEnum;
import com.ymttest.common.enums.BondedAreaEnum;
import com.ymttest.common.enums.OrderSourceEnum;
import com.ymttest.common.enums.OrderTypeEnum;
import com.ymttest.common.enums.PriceTypeEnum;
import com.ymttest.common.enums.ProductRefundChannelEnum;
import com.ymttest.common.enums.StockStatusEnum;
import com.ymttest.common.enums.TerminalSourceEnum;
import com.ymttest.database.model.PPBussinessOrder;
import com.ymttest.database.model.PPPayment;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.database.sqlwapper.PaymentDefaultWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.ECode;

/**
 * 新增支付接口 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_ChangePriceOrderPayRequest {
    private static OrderPayRequestBean orderpayrequestbean;

    private static OrderPayRequestCall orderpayrequestcall;

    @BeforeClass
    public static void setUp() {
        Logger.createResultFile("新增支付接口");
    }

    @Before
    public void caseUp() {
        orderpayrequestbean = new OrderPayRequestBean();
        orderpayrequestcall = new OrderPayRequestCall();

    }

    @AfterClass
    public static void tearDown() {
        Logger.generateResult(orderpayrequestcall.getOpurl());
    }

    @After
    public void caseDown() {
        Logger.end();
    }
    
    

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_OrderPayRequest_001() {
        Logger.start(true, "使用支付宝app第三方支付，验证第三方支付接口返回报文");
        try {
            // 创建订单
            Logger.comment("前置数据准备");
            Map map = new OrderCallService().createM2cOrder();
            Logger.comment("前置数据准备结束");
            int orderId = (Integer) map.get("orderId");
            int sellerId = (Integer) map.get("sellerId");
            int userId = (Integer) map.get("userId");
            int tradingId = (Integer) map.get("tradingId");
            BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");
            // 参数
            orderpayrequestbean.setCallBackUrl("www.ymtautotest.com");
            orderpayrequestbean.setUserId(userId);
            // orderpayrequestbean.setUseAccountAmount(price1);
            orderpayrequestbean.setTradingId(tradingId);
            String tradingPassword = EnvSetup.getData("tradingPassword");
            orderpayrequestbean.setTradingPwd(tradingPassword);
            orderpayrequestbean.setUserIp("127.0.0.10");
            orderpayrequestbean.setBankId("123");
            orderpayrequestbean.setPayType("13");
            orderpayrequestbean.setUsePlatform(PlatformEnum.SHANGOU_WAP.getValue());
            orderpayrequestbean.setParamExt("");
            orderpayrequestbean.setMemo("备注");
            // 发送请求
            orderpayrequestcall.setData(orderpayrequestbean);
            orderpayrequestcall.callService();
            Logger.verifyEquals(ECode.SUCCESS, orderpayrequestcall.getCode(), "验证Code");
            Logger.verifyEquals("JSON", orderpayrequestcall.getData().get("resultType"), "验证Code");
            Logger.comment("创建第三方支付订单结束");
            
            Logger.comment("修改订单折扣");
            BigDecimal discount = new BigDecimal(1);                  
            new OrderCallService().changeOrderDiscount(orderId, sellerId, discount);
           
            Logger.comment("支付回调"); 
            OrderPayCallBackReq orderPayCallBackBean = new OrderPayCallBackReq();
            orderPayCallBackBean.setAppId("1");
            orderPayCallBackBean.setBizCode("3");
            orderPayCallBackBean.setCurrency("CNY");
            orderPayCallBackBean.setMemo("autotest");
            BigDecimal blanceAmout = BigDecimal.ZERO.setScale(2);
            String payType = "13";
            int thirdTradingId = new OrderCallService().orderPayRequestInJava(userId, blanceAmout, tradingId, payType);
            orderPayCallBackBean.setTradingId(String.valueOf(thirdTradingId));
            orderPayCallBackBean.setPaymentId("radamnumber");
            // 此接口的价格不用传，因为接口不会按照这个参数进行支付。
            HashMap paymentInstruction = new HashMap();
            paymentInstruction =
                    new DefaultWapper().selectPaymentInstructionByNewtradingId(String.valueOf(thirdTradingId));
            String trackId = (String) paymentInstruction.get("id");
            orderPayCallBackBean.setPayPrice("price");
            orderPayCallBackBean.setPayTime("2015-09-09T22:53:22");
            orderPayCallBackBean.setSignMethod("");
            
            orderPayCallBackBean.setTraceId(trackId);
            orderPayCallBackBean.setInstPaymentId("radamInstPaymentId");
            orderPayCallBackBean.setInternalUserId("internaluseid");
            orderPayCallBackBean.setExternalUserId("radamuserId");
            orderPayCallBackBean.setPayChannel("Alipay");
            orderPayCallBackBean.setPayType("type");
            orderPayCallBackBean.setVersion(1);
            OrderPayCallBackCall orderPayCallBackCall = new OrderPayCallBackCall();
            // 发送请求
            orderPayCallBackCall.setData(orderPayCallBackBean);
            orderPayCallBackCall.callService();
            
            //数据库验证
            Logger.comment("数据库验证");
            
            
            DefaultWapper database = new DefaultWapper();
            String newTradingId = database.selectOrderByOderId(orderId).get(0).get("iTradingId")+"";
            BigDecimal fOrderPrice = (BigDecimal) database.selectOrderByOderId(orderId).get(0).get("fOrderPrice");
            BigDecimal fOrderDiscount = (BigDecimal) database.selectOrderByOderId(orderId).get(0).get("fOrderDiscount");
            BigDecimal oldPrice = fOrderPrice.add(fOrderDiscount);
            BigDecimal TotalAmount = (BigDecimal) database.selectPaymentInstructionByNewtradingId(newTradingId).get("TotalAmount");           
            Logger.verifyEquals(oldPrice, TotalAmount, "验证第三方支付修改折扣交易结算表");
        } catch (Exception e) {
            Logger.fail(e);
        }
    }


    /**
     * 验证alipayapp 返回
     * 
     * @param orderId
     * @throws Exception
     */
    private void verifyAlipayApp(int orderId) throws Exception {
        Logger.comment("验证支付宝APP Result报文");
        // 订单主表
        List<Map> ymtOrders = new DefaultWapper().selectOrderByOderId(orderId);
        // 第三方支付的金额=订单应付金额-使用余额支付的金额
        BigDecimal totalFee = new OrderCallService().getNeedPrePayAmountOfCash(orderId).subtract(
                orderpayrequestbean.getUseAccountAmount() == null ? BigDecimal.ZERO : orderpayrequestbean
                        .getUseAccountAmount());
        String productName = (String) ymtOrders.get(0).get("sBuyerLoginId") + "的订单";

        Map m = (Map) FormatUtil.GSONToObject(orderpayrequestcall.getData().getString("result"), Map.class);
        Logger.verifyNotNull(m.get("Sign"), "验证Sign非空");
        Logger.verifyEquals("2088701734809577", m.get("Partner"), "验证partner合作者身份ID");
        Logger.verifyEquals("ap.ymt@ymatou.com", m.get("SellerId"), "验证SellerId买家支付宝账号");
        PPBussinessOrder ppb = new PaymentDefaultWapper().selectPPBussinessorderByOrderId(
                orderpayrequestcall.getData().getString("tradingId")).get(0);
        String businessoid = ppb.getBussinessOrderId();
        PPPayment ppm = new PaymentDefaultWapper().selectPPPaymentByBussinessOrderId(businessoid).get(0);
        HashMap mext = (HashMap) FormatUtil.GSONToObject(ppb.getExt(), HashMap.class);
        int isHangzhou = 0;
        if (mext.size() > 0) {
            isHangzhou = Double.valueOf(mext.get("IsHangZhou").toString()).intValue();
        }
        String trandno = ppm.getPaymentId();
        Logger.verifyEquals(trandno, m.get("OutTradeNo"), "验证OutTradeNo");
        Logger.verifyEquals(productName, m.get("Subject"), "验证Subject");
        Logger.verifyEquals(true,
                TestDataManager.equalsBigDecimal(new BigDecimal(m.get("TotalFee").toString()), totalFee.toString()),
                "验证total_fee:" + m.get("TotalFee"));
        if (EnvSetup.getEnv().equals("sit1")) {
            Logger.verifyEquals(
                    "http://" + "sit" + ".payment.ymatou.com:8380/notify/"
                            + orderpayrequestbean.getPayType(),
                    m.get("NotifyUrl"), "验证NotifyUrl");
        }
        else if (EnvSetup.getEnv().equals("uat")) {
            Logger.verifyEquals(
                    "http://" + "uat" + ".payment.ymatou.com:8480/notify/"
                            + orderpayrequestbean.getPayType(),
                    m.get("NotifyUrl"), "验证NotifyUrl");
        }
        Logger.verifyEquals("mobile.securitypay.pay", m.get("Service"), "验证Service");
        Logger.verifyEquals("1", m.get("PaymentType"), "验证PaymentType");
        Logger.verifyEquals("utf-8", m.get("InputCharset"), "验证InputCharset");
        Logger.verifyEquals("10d", m.get("ItBPay"), "验证ItBPay");
        Logger.verifyEquals("RSA", m.get("SignType"), "验证SignType");
        Logger.verifyEquals(true, m.get("QuerySuccess"), "验证QuerySuccess");
        Logger.verifyEquals("成功", m.get("Message"), "验证Message");
        Logger.comment("验证EncryptStr");
        Map mencrypt = FormatUtil.httpStringToMap(m.get("EncryptStr").toString());
        Logger.verifyNotNull(mencrypt.get("sign"), "验证Sign非空");
        Logger.verifyEquals("2088701734809577", mencrypt.get("partner"), "验证partner合作者身份ID");
        Logger.verifyEquals("ap.ymt@ymatou.com", mencrypt.get("seller_id"), "验证seller_id买家支付宝账号");
        Logger.verifyEquals(trandno, mencrypt.get("out_trade_no"), "验证out_trade_no");
        Logger.verifyEquals(productName, mencrypt.get("subject"), "验证subject");
        Logger.verifyEquals(
                true,
                TestDataManager.equalsBigDecimal(new BigDecimal(mencrypt.get("total_fee").toString()),
                        totalFee.toString()), "验证total_fee:" + mencrypt.get("total_fee"));
        if (EnvSetup.getEnv().equals("sit1")) {
            Logger.verifyEquals(
                    "http://" + "sit" + ".payment.ymatou.com:8380/notify/"
                            + orderpayrequestbean.getPayType(),
                    mencrypt.get("notify_url"), "验证notify_url");
        }
        else if (EnvSetup.getEnv().equals("uat")) {
            Logger.verifyEquals(
                    "http://" + "uat" + ".payment.ymatou.com:8480/notify/"
                            + orderpayrequestbean.getPayType(),
                    mencrypt.get("notify_url"), "验证notify_url");
        }
        Logger.verifyEquals("mobile.securitypay.pay", mencrypt.get("service"), "验证service");
        Logger.verifyEquals("1", mencrypt.get("payment_type"), "验证payment_type");
        Logger.verifyEquals("utf-8", mencrypt.get("_input_charset"), "验证_input_charset");
        Logger.verifyEquals("10d", mencrypt.get("it_b_pay"), "验证it_b_pay");
        Logger.verifyEquals("RSA", mencrypt.get("sign_type"), "验证sign_type");
        Logger.verifyEquals("m.alipay.com", mencrypt.get("show_url"), "验证show_url");
        // 杭保实名，非杭保不验
        if (isHangzhou == 1) {
            Logger.verifyEquals("T", mencrypt.get("rn_check"), "验证rn_check");
        }
        Logger.verifyNotNull(mencrypt.get("sign"), "验证sign非空");
    }

    /**
     * 校验Html Form返回 支付宝PC支付
     * 
     * @param orderId
     * @throws Exception
     */
    private void verifyHtmlResult(int orderId) throws Exception {
        Logger.comment("验证支付宝PC Result");
        Map m = new HashMap<String, String>();
        // 订单主表
        List<Map> ymtOrders = new DefaultWapper().selectOrderByOderId(orderId);
        BigDecimal totalFee = ((BigDecimal) ymtOrders.get(0).get("fOrderPrice")).add(((BigDecimal) ymtOrders.get(0)
                .get("fFreight")));
        String productName = (String) ymtOrders.get(0).get("sBuyerLoginId") + "的订单";
        // 返回报文result
        String result = orderpayrequestcall.getData().getString("result");
        List<String> namelist = TestDataManager.getRegexList(result, "(?<=name=\").*?(?=\")");
        List<String> valuelist = TestDataManager.getRegexList(result, "(?<=value=\").*?(?=\")");
        if (valuelist.size() == namelist.size()) {
            for (int i = 0; i < namelist.size(); i++) {
                m.put(namelist.get(i), valuelist.get(i));
            }
        } else {
            throw new Exception("verifyResult失败，结果集name value 不匹配");
        }
        PPBussinessOrder ppb = new PaymentDefaultWapper().selectPPBussinessorderByOrderId(
                orderpayrequestcall.getData().getString("tradingId")).get(0);

        HashMap mext = (HashMap) FormatUtil.GSONToObject(ppb.getExt(), HashMap.class);
        int isHangzhou = Double.valueOf(mext.get("IsHangZhou").toString()).intValue();

        String businessoid = ppb.getBussinessOrderId();
        PPPayment ppm = new PaymentDefaultWapper().selectPPPaymentByBussinessOrderId(businessoid).get(0);
        String trandno = ppm.getPaymentId();
        Logger.verifyEquals(productName, m.get("subject"), "验证subject");
        Logger.verifyEquals("MD5", m.get("sign_type"), "验证sign_type");

        if (EnvSetup.getEnv().equals("sit1")) {
            Logger.verifyEquals(
                    "http://" + "sit" + ".payment.ymatou.com:8380/notify/"
                            + orderpayrequestbean.getPayType(),
                    m.get("notify_url"), "验证notify_url");
            Logger.verifyEquals(trandno, m.get("out_trade_no"), "验证out_trade_no");
            Logger.verifyEquals(
                    "http://" + "sit" + ".payment.ymatou.com:8380/callback/"
                            + orderpayrequestbean.getPayType(),
                    m.get("return_url"), "验证return_url");
        }
        else if (EnvSetup.getEnv().equals("uat")) {
            Logger.verifyEquals(
                    "http://" + "uat" + ".payment.ymatou.com:8480/notify/"
                            + orderpayrequestbean.getPayType(),
                    m.get("notify_url"), "验证notify_url");
            Logger.verifyEquals(trandno, m.get("out_trade_no"), "验证out_trade_no");
            Logger.verifyEquals(
                    "http://" + "uat" + ".payment.ymatou.com:8480/callback/"
                            + orderpayrequestbean.getPayType(),
                    m.get("return_url"), "验证return_url");
        }

        // sign算法未知
        Logger.verifyNotNull(m.get("sign"), "验证sign非空");
        Logger.verifyEquals("utf-8", m.get("_input_charset"), "验证_input_charset");
        Logger.verifyEquals(orderpayrequestbean.getUserIp(), m.get("exter_invoke_ip"), "验证exter_invoke_ip");
        Logger.verifyEquals(true,
                TestDataManager.equalsBigDecimal(new BigDecimal(m.get("total_fee").toString()), totalFee.toString()),
                "验证total_fee:" + m.get("total_fee"));
        if (isHangzhou == 1) {
            Logger.comment("验证杭保信息");
            Logger.verifyEquals("{&quot;needBuyerRealnamed&quot;:&quot;T&quot;}", m.get("buyer_info"),
                    "验证buyer_info买家信息");
            Logger.verifyEquals("alipay.acquire.page.createandpay", m.get("service"), "验证service统一下单并支付");
            Logger.verifyEquals("FAST_INSTANT_TRADE_PAY", m.get("product_code"), "验证product_code订单业务类型");
        } else {
            Logger.comment("验证非杭保信息");
            Logger.verifyEquals(orderpayrequestbean.getBankId(), m.get("defaultbank"), "验证defaultbank默认银行");
            Logger.verifyEquals("create_direct_pay_by_user", m.get("service"), "验证service统一下单并支付");
            Logger.verifyEquals(ppb.getThirdPartyUserId() == null ? "N" : "Y", m.get("default_login"),
                    "验证default_login默认登录");
        }
        // 固定
        Logger.verifyEquals("2088701734809577", m.get("partner"), "验证partner合作者身份ID");
        Logger.verifyNotNull(m.get("anti_phishing_key"), "验证anti_phishing_key防钓鱼时间戳");
        Logger.verifyEquals("ap.ymt@ymatou.com", m.get("seller_email"), "验证seller_email买家支付宝账号");
        Logger.verifyEquals("1", m.get("payment_type"), "验证payment_type 1（商品购买）");
    }

    /**
     * 校验weixin 微信-JSAPI
     * 
     * @param orderId
     * @throws Exception
     */
    private void verifyWeixin() {
        try {
            Logger.comment("验证微信JSAPI Result报文");
            HashMap mresult = (HashMap) FormatUtil.GSONToObject(orderpayrequestcall.getData().getString("result"),
                    HashMap.class);
            Logger.verifyNotNull(mresult.get("AppID"), "验证AppID 公众号");
            Logger.verifyNotNull(mresult.get("TimeStamp"), "验证TimeStamp非空");
            Logger.verifyNotNull(mresult.get("NonceStr"), "验证NonceStr非空");
            Logger.verifyNotNull(mresult.get("Package"), "验证Package非空");
            String sign = null;
            String mysign = null;
            if (orderpayrequestbean.getPayType().equals("15")) {
                Logger.verifyEquals("Sign=WXPay", mresult.get("Package"), "验证SignType");
                sign = mresult.get("Sign").toString();
                String merchantId = mresult.get("MerchantId").toString();
                Map resetmap = new TreeMap();
                resetmap.put("appid", mresult.get("AppID"));
                resetmap.put("partnerid", mresult.get("MerchantId"));
                resetmap.put("prepayid", mresult.get("PayToken"));
                resetmap.put("timestamp", mresult.get("TimeStamp"));
                resetmap.put("package", mresult.get("Package"));
                resetmap.put("noncestr", mresult.get("NonceStr"));
                Logger.debug("15 resetmap:" + resetmap);
                mysign = new Sign().signMd5(resetmap, Sign.weixinAppKey);
            } else if (orderpayrequestbean.getPayType().equals("14")) {
                Logger.verifyEquals("MD5", mresult.get("SignType"), "验证SignType");
                sign = mresult.get("Sign").toString();
                Map resetmap = new TreeMap();
                resetmap.put("appId", mresult.get("AppID"));
                resetmap.put("timeStamp", mresult.get("TimeStamp"));
                resetmap.put("package", mresult.get("Package"));
                resetmap.put("nonceStr", mresult.get("NonceStr"));
                resetmap.put("signType", mresult.get("SignType"));
                Logger.debug("14 resetmap:" + resetmap);
                mysign = new Sign().signMd5(resetmap, Sign.weixinJSAPIKey);
            }
            Logger.verifyEquals(mysign.toLowerCase(), sign.toLowerCase(), "验证Sign");
        } catch (Exception e) {
        }
    }


    

    private void verifyDb(int orderId) {
        // 交易号
        int tradingId = orderpayrequestbean.getTradingId();
        // 用户id
        int userId = orderpayrequestbean.getUserId();
        // 用户支付的余额
        BigDecimal payAmount = orderpayrequestbean.getUseAccountAmount().setScale(2);

        DefaultWapper database = new DefaultWapper();
        // 订单主表
        List<Map> ymtOrders = database.selectOrderByOderId(orderId);
        // 订单商品明细
        List<Map> ymtOrdersInfoList = database.selectOrderInfoByOderId(orderId);
        // ymt_tradinginfo 表
        List<Map> ymtTradinginfo = database.selectTradinginfoByTradingId(tradingId);
        // ymtOrderState 表
        List<Map> ymtOrderState = database.selectOrderStateByOderId(orderId);
        // ymt_orderpay 表
        List<Map> ymtOrderPay = database.selectOrderPay(orderId);
        // 订单定金金额
        BigDecimal orderPrice = (BigDecimal) ymtOrders.get(0).get("fOrderPrice");
        // 运费
        BigDecimal freight = (BigDecimal) ymtOrders.get(0).get("fFreight");
        // 优惠券金额
        BigDecimal couponValue = (BigDecimal) ymtOrders.get(0).get("CouponValue");
        // 商家用户优惠券金额
        BigDecimal sellerCouponValue = (BigDecimal) ymtOrders.get(0).get("fSellerCouponAmount");
        // 平台用户优惠券金额
        BigDecimal ymtCouponValue = (BigDecimal) ymtOrders.get(0).get("fYmtCouponAmount");

        // 订单应付金额
        BigDecimal needPayAmount = orderPrice.add(freight).subtract(couponValue);
        Logger.comment("验证订单号:" + orderId);
        Logger.comment("验证ymt_order表");
        Logger.verifyEquals(
                2,
                (Integer) ymtOrders.get(0).get("iTradingStatus"), "验证iTradingStatus");

        Logger.comment("验证ymt_orderState表");
        Logger.verifyEquals(1, ymtOrderState.size(), "验证ymt_orderState表");
        Logger.verifyEquals(
                couponValue,
                (BigDecimal) ymtOrderState.get(0).get("fPaidAmountOfCoupon"), "验证fPaidAmountOfCoupon");
        Logger.verifyEquals(
                needPayAmount,
                (BigDecimal) ymtOrderState.get(0).get("fPaidAmountOfCash"), "验证fPaidAmountOfCash");
        Logger.verifyEquals(
                sellerCouponValue,
                (BigDecimal) ymtOrderState.get(0).get("fPaidAmountOfSellerCoupon"), "验证fPaidAmountOfSellerCoupon");
        Logger.verifyEquals(
                ymtCouponValue,
                (BigDecimal) ymtOrderState.get(0).get("fPaidAmountOfYmtCoupon"), "验证fPaidAmountOfYmtCoupon");
        Logger.verifyEquals(
                needPayAmount,
                (BigDecimal) ymtOrderState.get(0).get("fPaidAmountOfYmtAccount"), "验证fPaidAmountOfYmtAccount");

        Logger.comment("验证ymt_orderpay表");
        Logger.verifyEquals(
                tradingId,
                (Integer) ymtOrderPay.get(0).get("iTradingId"), "验证iTradingId");
        Logger.verifyEquals(
                1,
                (Integer) ymtOrderPay.get(0).get("iPayType"), "验证iPayType");
        Logger.verifyEquals(
                needPayAmount,
                (BigDecimal) ymtOrderPay.get(0).get("fAmount"), "验证fAmount");
        Logger.verifyEquals(
                0,
                (Integer) ymtOrderPay.get(0).get("iStatus"), "验证iStatus");
        Logger.verifyEquals(
                "支付成功_余额",
                (String) ymtOrderPay.get(0).get("sMemo"), "验证sMemo");
        Logger.verifyEquals(
                0,
                (Integer) ymtOrderPay.get(0).get("iAccountingNum"), "验证iAccountingNum");
        Logger.verifyEquals(
                "操作成功！",
                (String) ymtOrderPay.get(0).get("sAccountingMessage"), "验证sAccountingMessage");
    }

    /**
     * 校验Html Form返回 支付宝PC支付
     * 
     * @param orderId
     * @throws Exception
     */
    private void verifyHtmlResult(int orderId, BigDecimal needThirdPayAmount) throws Exception {
        Logger.comment("验证支付宝PC Result");
        Map m = new HashMap<String, String>();
        // 订单主表
        List<Map> ymtOrders = new DefaultWapper().selectOrderByOderId(orderId);
        BigDecimal totalFee = needThirdPayAmount;
        String productName = (String) ymtOrders.get(0).get("sBuyerLoginId") + "的订单";
        // 返回报文result
        String result = orderpayrequestcall.getData().getString("result");
        List<String> namelist = TestDataManager.getRegexList(result, "(?<=name=\").*?(?=\")");
        List<String> valuelist = TestDataManager.getRegexList(result, "(?<=value=\").*?(?=\")");
        if (valuelist.size() == namelist.size()) {
            for (int i = 0; i < namelist.size(); i++) {
                m.put(namelist.get(i), valuelist.get(i));
            }
        } else {
            throw new Exception("verifyResult失败，结果集name value 不匹配");
        }
        PPBussinessOrder ppb = new PaymentDefaultWapper().selectPPBussinessorderByOrderId(
                orderpayrequestcall.getData().getString("tradingId")).get(0);

        HashMap mext = (HashMap) FormatUtil.GSONToObject(ppb.getExt(), HashMap.class);
        int isHangzhou = Double.valueOf(mext.get("IsHangZhou").toString()).intValue();

        String businessoid = ppb.getBussinessOrderId();
        PPPayment ppm = new PaymentDefaultWapper().selectPPPaymentByBussinessOrderId(businessoid).get(0);
        String trandno = ppm.getPaymentId();
        Logger.verifyEquals(productName, m.get("subject"), "验证subject");
        Logger.verifyEquals("MD5", m.get("sign_type"), "验证sign_type");
        if (EnvSetup.getEnv().equals("sit1")) {
            Logger.verifyEquals(
                    "http://" + "sit" + ".payment.ymatou.com:8380/notify/"
                            + orderpayrequestbean.getPayType(),
                    m.get("notify_url"), "验证notify_url");
            Logger.verifyEquals(
                    "http://" + "sit" + ".payment.ymatou.com:8380/callback/"
                            + orderpayrequestbean.getPayType(),
                    m.get("return_url"), "验证return_url");
        }
        else if (EnvSetup.getEnv().equals("uat")) {
            Logger.verifyEquals(
                    "http://" + "uat" + ".payment.ymatou.com:8480/notify/"
                            + orderpayrequestbean.getPayType(),
                    m.get("notify_url"), "验证notify_url");
            Logger.verifyEquals(
                    "http://" + "uat" + ".payment.ymatou.com:8480/callback/"
                            + orderpayrequestbean.getPayType(),
                    m.get("return_url"), "验证return_url");
        }
        Logger.verifyEquals(trandno, m.get("out_trade_no"), "验证out_trade_no");

        // sign算法未知
        Logger.verifyNotNull(m.get("sign"), "验证sign非空");
        Logger.verifyEquals("utf-8", m.get("_input_charset"), "验证_input_charset");
        Logger.verifyEquals(orderpayrequestbean.getUserIp(), m.get("exter_invoke_ip"), "验证exter_invoke_ip");
        Logger.verifyEquals(true,
                TestDataManager.equalsBigDecimal(new BigDecimal(m.get("total_fee").toString()), totalFee.toString()),
                "验证total_fee:" + m.get("total_fee"));
        if (isHangzhou == 1) {
            Logger.comment("验证杭保信息");
            Logger.verifyEquals("{&quot;needBuyerRealnamed&quot;:&quot;T&quot;}", m.get("buyer_info"),
                    "验证buyer_info买家信息");
            Logger.verifyEquals("alipay.acquire.page.createandpay", m.get("service"), "验证service统一下单并支付");
            Logger.verifyEquals("FAST_INSTANT_TRADE_PAY", m.get("product_code"), "验证product_code订单业务类型");
        } else {
            Logger.comment("验证非杭保信息");
            Logger.verifyEquals(orderpayrequestbean.getBankId(), m.get("defaultbank"), "验证defaultbank默认银行");
            Logger.verifyEquals("create_direct_pay_by_user", m.get("service"), "验证service统一下单并支付");
            Logger.verifyEquals(ppb.getThirdPartyUserId() == null ? "N" : "Y", m.get("default_login"),
                    "验证default_login默认登录");
        }
        // 固定
        Logger.verifyEquals("2088701734809577", m.get("partner"), "验证partner合作者身份ID");
        Logger.verifyNotNull(m.get("anti_phishing_key"), "验证anti_phishing_key防钓鱼时间戳");
        Logger.verifyEquals("ap.ymt@ymatou.com", m.get("seller_email"), "验证seller_email买家支付宝账号");
        Logger.verifyEquals("1", m.get("payment_type"), "验证payment_type 1（商品购买）");
    }

    // 一次下单生成2个订单号,分别使用平台,商家优惠券,每个订单下面3个商品
    private Map placeOrder() {
        Map map = new HashMap();
        try {
            PlaceOrderBean placeorderBean = new PlaceOrderBean();
            PlaceOrderCall placeorderCall = new PlaceOrderCall();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            // 创建产品
            Logger.comment("前置数据准备");
            HashMap<String, Object> productInfo = ProductCallService.createProduct(sellerId, 3);
            Logger.comment("前置数据准备结束");
            String productId = (String) productInfo.get("productId");
            Logger.debug("productId:" + productId);
            String productName = (String) productInfo.get("productName");
            String pic = (String) productInfo.get("pic");
            BigDecimal price = (BigDecimal) (productInfo.get("price"));
            // String catalogId = (String) productInfo.get("catalogId");
            // 买家用户等级
            int userLevel = 3;
            // 订单来源
            int orderSource = OrderSourceEnum.APP.getValue();
            placeorderBean.setOrderSource(orderSource);
            // 终端来源
            int terminalSource = TerminalSourceEnum.IOS.getValue();
            placeorderBean.setTerminalSource(terminalSource);
            // 应用终端来源
            int appTerminalSource = AppTerminalSourceEnum.Phone.getValue();
            placeorderBean.setAppTerminalSource(appTerminalSource);
            // SourceIp
            String sourceIp = "127.0.0.1";
            placeorderBean.setSourceIp(sourceIp);
            // 用户设备号
            String deviceId = "";
            placeorderBean.setDeviceId(deviceId);
            // 订单信息List
            List<OrderInfo> orderInfoList = new ArrayList<OrderInfo>();
            OrderInfo order = new OrderInfo();
            // 订单类型
            int orderType = OrderTypeEnum.Shangou.getValue();
            order.setOrderType(orderType);
            // 卖家
            order.setSellerId(sellerId);
            String leaveWord = "autotest";
            order.setLeaveWord(leaveWord);
            // 运费
            BigDecimal freight = new BigDecimal(23);
            order.setFreight(freight);
            // 优惠券
            // 领用优惠券
            BigDecimal couponValue = new BigDecimal(10);
            // 领用商家优惠券
            String couponCode = new CouponCallService().receiveCouponInfo(sellerId, userId, couponValue);
            order.setCouponCode(couponCode);
            // 优惠券类型
            int couponType = 1;
            order.setCouponUseType(couponType);
            // 优惠券渠道
            int couponChannel = 2;
            order.setCouponChannel(couponChannel);
            // 优惠券金额
            order.setCouponValue(couponValue);
            // 是否全额付款
            boolean isPaidFull = false;
            order.setIsPaidFull(isPaidFull);
            // 收货地址
            String address = "上海市闸北区灵石路636号";
            order.setAddress(address);
            // 邮编
            String postCode = "200001";
            order.setPostCode(postCode);
            // 收件人姓名
            String receieveName = "李四";
            order.setReceieveName(receieveName);
            // 收货人手机号
            String phone = "13100000001";
            order.setPhone(phone);
            // 收货人电话
            String telephone = "021-51002100";
            order.setTelephone(telephone);
            // 自动取消小时数
            BigDecimal autoCancelOrderHours = new BigDecimal(10);
            order.setAutoCancelOrderHours(autoCancelOrderHours);
            // 订单商品信息
            List<OrderProductInfo> orderProductInfoList = new ArrayList<OrderProductInfo>();
            OrderProductInfo productinfo = new OrderProductInfo();
            OrderProductInfo productinfo2 = new OrderProductInfo();
            OrderProductInfo productinfo3 = new OrderProductInfo();
            // 商品id
            productinfo.setProductId(productId);
            // 商品名称
            productinfo.setProductName(productName);
            // 商品规格id
            String catalogId = TestDataManager.getRandomUUID().toString();
            productinfo.setCatalogId(catalogId);
            // 备货状态(1-现货 2-代购 3-FBX)
            int catalogType = StockStatusEnum.Spot.getValue();
            productinfo.setStockStatusEnum(catalogType);
            // 商品数量
            int productNum = 1 + new Random().nextInt(5);
            productinfo.setProductNum(productNum);
            // 商品一级目录id
            int firstCategoryId = 1;
            productinfo.setFirstCategoryId(firstCategoryId);
            // 商品一级目录id
            int secondCategoryId = 2;
            productinfo.setSecondCategoryId(secondCategoryId);
            // 商品一级目录id
            int thirdCategoryId = 3;
            productinfo.setThirdCategoryId(thirdCategoryId);
            // 商品品牌id
            int brandId = 5;
            productinfo.setBrandId(brandId);
            // 商品url
            productinfo.setPictureUrl(pic);
            // 商品属性信息(按JSON格式存储，如--颜色:黑色,尺寸:XXS)
            String propetyInfo = "";
            productinfo.setPropetyInfo(propetyInfo);
            // 商品价格
            BigDecimal productPrice = price;
            productinfo.setProductPrice(productPrice);
            // 商品预付定金价格
            BigDecimal earnestPrice = price.divide(new BigDecimal(3), 2, BigDecimal.ROUND_HALF_UP); // 小数点后保留2位并四舍五入
            productinfo.setEarnestPrice(earnestPrice);
            // 价格类型
            int priceType = PriceTypeEnum.Unkown.getValue();
            productinfo.setPriceType(priceType);
            // 买家或卖家承担关税(0-卖家承担 1-买家承担)
            int tariffType = 0;
            productinfo.setTariffType(tariffType);
            // 物流类型
            int logisticsType = LogisticsTypeEnum.SailProtect.getCode();
            productinfo.setLogisticsType(logisticsType);
            // 保税区
            int bondedArea = BondedAreaEnum.NingBo.getValue();
            productinfo.setBondedArea(bondedArea);
            // 商品备案号
            String productRecordNo = "123456";
            productinfo.setProductRecordNo(productRecordNo);
            // SKU
            String sku = "1234567";
            productinfo.setSKU(sku);
            // 套餐编号
            String packageNo = "11111111";
            productinfo.setPackageNo(packageNo);
            // 商品退货渠道
            int productRefundChannel = ProductRefundChannelEnum.Official.getValue();
            productinfo.setProductRefundChannel(productRefundChannel);
            // 商品信息(存储格式为：Json格式)
            String productDetailInfo =
                    "e5a1eccf-6a14-458f-b907-35dc9a3d2713#适用人群:b13e9eb1-98d6-4d39-8c35-225758e443d3#男";
            productinfo.setProductDetailInfo(productDetailInfo);
            // 活动商品信息
            ProductActivityInfo activityInfo = new ProductActivityInfo();
            // 商品活动号
            int activityId = 46870;
            activityInfo.setActivityId(activityId);
            // 额外费用
            BigDecimal premium = new BigDecimal(10);
            activityInfo.setPremium(premium);
            // 是否算入成本价
            boolean isCost = false;
            activityInfo.setIsCost(isCost);
            // 是否使用优惠券
            boolean isUseCoupon = false;
            activityInfo.setIsUseCoupon(isUseCoupon);
            // 是否免佣金
            boolean isFeeFree = false;
            activityInfo.setIsFeeFree(isFeeFree);
            // 活动开始时间
            String beginDate = YMTDateUtil.getBeforeOrNextDay(-100);
            activityInfo.setActivityBeginDate(beginDate);
            // 活动结束时间
            String endDate = YMTDateUtil.getBeforeOrNextDay(10);
            activityInfo.setActivityEndDate(endDate);
            // 商品活动模板号
            int activityTemplateId = 987654;
            activityInfo.setActivityTemplateId(activityTemplateId);
            // 商品活动促销类型
            int promotionType = ActivityPromotionTypeEnum.DiscountPrice.getValue();
            activityInfo.setPromotionType(promotionType);
            // 促销价格
            BigDecimal promotionPrice = new BigDecimal(1);
            activityInfo.setPromotionPrice(promotionPrice);
            // 促销价格
            BigDecimal commissionRate = new BigDecimal(0);
            activityInfo.setCommissionRate(commissionRate);
            productinfo.setActivityInfo(activityInfo);
            // 第二件商品
            // 商品id
            productinfo2.setProductId(productId);
            // 商品名称
            productinfo2.setProductName(productName);
            // 商品规格id
            String catalogId2 = TestDataManager.getRandomUUID().toString();
            productinfo2.setCatalogId(catalogId2);
            // 备货状态(1-现货 2-代购 3-FBX)
            int catalogType2 = StockStatusEnum.Spot.getValue();
            productinfo2.setStockStatusEnum(catalogType2);
            // 商品数量
            int productNum2 = 1 + new Random().nextInt(5);
            productinfo2.setProductNum(productNum2);
            // 商品一级目录id
            int firstCategoryId2 = 1;
            productinfo2.setFirstCategoryId(firstCategoryId2);
            // 商品一级目录id
            int secondCategoryId2 = 2;
            productinfo2.setSecondCategoryId(secondCategoryId2);
            // 商品一级目录id
            int thirdCategoryId2 = 3;
            productinfo2.setThirdCategoryId(thirdCategoryId2);
            // 商品品牌id
            int brandId2 = 3;
            productinfo2.setBrandId(brandId2);
            // 商品url
            productinfo2.setPictureUrl(pic);
            // 商品属性信息(按JSON格式存储，如--颜色:黑色,尺寸:XXS)
            String propetyInfo2 = "";
            productinfo2.setPropetyInfo(propetyInfo2);
            // 商品价格
            BigDecimal productPrice2 = price;
            productinfo2.setProductPrice(productPrice2);
            // 商品预付定金价格
            BigDecimal earnestPrice2 = price.divide(new BigDecimal(3), 2, BigDecimal.ROUND_HALF_UP); // 小数点后保留2位并四舍五入
            productinfo2.setEarnestPrice(earnestPrice2);
            // 价格类型
            int priceType2 = PriceTypeEnum.NewPersonPrice.getValue();
            productinfo2.setPriceType(priceType2);
            // 买家或卖家承担关税(0-卖家承担 1-买家承担)
            int tariffType2 = 0;
            productinfo2.setTariffType(tariffType2);
            // 物流类型
            int logisticsType2 = LogisticsTypeEnum.XloboBondedDelivery.getCode();
            productinfo2.setLogisticsType(logisticsType2);
            // 保税区
            int bondedArea2 = BondedAreaEnum.NingBo.getValue();
            productinfo2.setBondedArea(bondedArea2);
            // 商品备案号
            String productRecordNo2 = "123456";
            productinfo2.setProductRecordNo(productRecordNo2);
            // SKU
            String sku2 = "1234567";
            productinfo2.setSKU(sku2);
            // 套餐编号
            String packageNo2 = "11111111";
            productinfo2.setPackageNo(packageNo2);
            // 商品退货渠道
            int productRefundChannel2 = ProductRefundChannelEnum.Official.getValue();
            productinfo2.setProductRefundChannel(productRefundChannel2);
            // 商品信息(存储格式为：Json格式)
            String productDetailInfo2 =
                    "e5a1eccf-6a14-458f-b907-35dc9a3d2713#适用人群:b13e9eb1-98d6-4d39-8c35-225758e443d3#男";
            productinfo2.setProductDetailInfo(productDetailInfo2);
            productinfo2.setActivityInfo(activityInfo);
            // 第三件商品
            // 商品id
            productinfo3.setProductId(productId);
            // 商品名称
            productinfo3.setProductName(productName);
            // 商品规格id
            String catalogId3 = TestDataManager.getRandomUUID().toString();
            productinfo3.setCatalogId(catalogId3);
            // 备货状态(1-现货 2-代购 3-FBX)
            productinfo3.setStockStatusEnum(catalogType);
            // 商品数量
            int productNum3 = 1 + new Random().nextInt(5);
            productinfo3.setProductNum(productNum3);
            // 商品一级目录id
            productinfo3.setFirstCategoryId(firstCategoryId);
            // 商品一级目录id
            productinfo3.setSecondCategoryId(secondCategoryId);
            // 商品一级目录id
            productinfo3.setThirdCategoryId(thirdCategoryId);
            // 商品品牌id
            int brandId3 = 3;
            productinfo3.setBrandId(brandId3);
            // 商品url
            productinfo3.setPictureUrl(pic);
            // 商品属性信息(按JSON格式存储，如--颜色:黑色,尺寸:XXS)
            String propetyInfo3 = "";
            productinfo3.setPropetyInfo(propetyInfo3);
            // 商品价格
            BigDecimal productPrice3 = price;
            productinfo3.setProductPrice(productPrice3);
            // 商品预付定金价格
            BigDecimal earnestPrice3 = price.divide(new BigDecimal(3), 2, BigDecimal.ROUND_HALF_UP); // 小数点后保留2位并四舍五入
            productinfo3.setEarnestPrice(earnestPrice3);
            // 价格类型
            int priceType3 = PriceTypeEnum.NewPersonPrice.getValue();
            productinfo3.setPriceType(priceType3);
            // 买家或卖家承担关税(0-卖家承担 1-买家承担)
            int tariffType3 = 0;
            productinfo3.setTariffType(tariffType3);
            // 物流类型
            int logisticsType3 = LogisticsTypeEnum.XloboBondedDelivery.getCode();
            productinfo3.setLogisticsType(logisticsType3);
            // 保税区
            int bondedArea3 = BondedAreaEnum.NingBo.getValue();
            productinfo3.setBondedArea(bondedArea3);
            // 商品备案号
            productinfo3.setProductRecordNo(productRecordNo);
            // SKU
            productinfo3.setSKU(sku);
            // 套餐编号
            productinfo3.setPackageNo(packageNo);
            // 商品退货渠道
            productinfo3.setProductRefundChannel(productRefundChannel);
            // 商品信息(存储格式为：Json格式)
            productinfo3.setProductDetailInfo(productDetailInfo);
            // 活动商品信息
            productinfo3.setActivityInfo(activityInfo);

            orderProductInfoList.add(productinfo);
            orderProductInfoList.add(productinfo2);
            orderProductInfoList.add(productinfo3);
            // 订单商品信息
            order.setOrderProductInfoList(orderProductInfoList);
            // 第二个订单
            OrderInfo order2 = new OrderInfo();
            // 订单类型
            int orderType2 = OrderTypeEnum.Shangou.getValue();
            order2.setOrderType(orderType2);
            // 卖家
            order2.setSellerId(sellerId);
            String leaveWord2 = "autotest";
            order2.setLeaveWord(leaveWord2);
            // 运费
            BigDecimal freight2 = new BigDecimal(20);
            order2.setFreight(freight2);
            // 优惠券
            BigDecimal couponValue2 = new BigDecimal(11);
            // ymt 平台优惠券
            String couponCode2 = new OrderCallService().receivePlatformCoupon(userId, couponValue);
            order2.setCouponCode(couponCode2);
            // 优惠券类型
            int couponType2 = 1;
            order2.setCouponUseType(couponType2);
            // 优惠券渠道 1 ymt平台，2 商家
            int couponChannel2 = 1;
            order2.setCouponChannel(couponChannel2);
            // 优惠券金额
            order2.setCouponValue(couponValue2);
            // 是否全额付款
            boolean isPaidFull2 = false;
            order2.setIsPaidFull(isPaidFull2);
            // 收货地址
            String address2 = "上海市闸北区灵石路636号";
            order2.setAddress(address2);
            // 邮编
            String postCode2 = "200001";
            order2.setPostCode(postCode2);
            // 收件人姓名
            String receieveName2 = "李四";
            order2.setReceieveName(receieveName2);
            // 收货人手机号
            String phone2 = "13100000002";
            order2.setPhone(phone2);
            // 收货人电话
            String telephone2 = "021-51002111";
            order2.setTelephone(telephone2);
            // 自动取消小时数
            BigDecimal autoCancelOrderHours2 = new BigDecimal(2);
            order2.setAutoCancelOrderHours(autoCancelOrderHours2);
            // 订单商品信息 拷贝第一单3个商品
            order2.setOrderProductInfoList(orderProductInfoList);
            // 订单信息
            orderInfoList.add(order);
            // 订单信息
            orderInfoList.add(order2);
            placeorderBean.setUserId(userId);
            placeorderBean.setOrderInfoList(orderInfoList);
            placeorderCall.setData(placeorderBean);
            placeorderCall.callService();
            JSONArray orders = placeorderCall.getOrderIds();
            int tradingId = placeorderCall.getTradingId();
            map.put("orders", orders);
            map.put("tradingId", tradingId);
        } catch (Exception e) {
            Logger.fail(e);
        }
        return map;
    }
}
